package csc.traning.wpsj.servlet;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import csc.traning.wpsj.dao.DirectoryLevel;
import csc.traning.wpsj.dao.FileInformation;
import csc.traning.wpsj.dao.User;
import csc.traning.wpsj.servlet.lessons.CookieUtilities;
import csc.traning.wpsj.servlet.lessons.FileUtilities;

public class FileManagementServlet extends HttpServlet {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession sess = req.getSession(false);
		User user = (User) sess.getAttribute("user");
		String userPath = "users/" + user.getUserName() + "/file_uploaded";

		String realUserPath = getServletContext().getRealPath(userPath);

		File userDir = new File(realUserPath);
		long allFileSize = (long) FileUtilities.getAllFileSize(userDir);
		long limitCapacity = (long) Long.parseLong(this.getServletContext()
				.getInitParameter("CapacityLimitSize"));
		limitCapacity = limitCapacity * 1024L;
		double to = (double) allFileSize / limitCapacity * 100.0;
		DecimalFormat df = new DecimalFormat("#.##");
		String usedCapacity = df.format(to);
		sess.setAttribute("percent", usedCapacity);

		if (!userDir.isDirectory()) {
			userDir.mkdirs();
		}

		String newPath;
		String requestPath = req.getParameter("subdir");
		if (requestPath == null) {

			if (req.getAttribute("forwardDir") != null) {
				requestPath = (String) req.getAttribute("forwardDir");
			}
		}

		if (requestPath == null) {
			newPath = realUserPath;
		} else {
			newPath = realUserPath + requestPath;

		}
		File dir = new File(newPath);

		File[] fileList = dir.listFiles();
		ArrayList<FileInformation> fileInfo = new ArrayList<FileInformation>();

		if (fileList.length > 0) {
			for (int i = 0; i < fileList.length; i++) {
				FileInformation temp = new FileInformation();
				if (fileList[i].isDirectory()) {
					temp.setPath(requestPath);
					temp.setName(fileList[i].getName());
					temp.setIsDirectory(true);
					fileInfo.add(temp);
				} else {
					temp.setPath(requestPath);
					temp.setName(fileList[i].getName());
					temp.setIsDirectory(false);
					temp.setSize(fileList[i].length());
					SimpleDateFormat sdf = new SimpleDateFormat(
							"dd/MM/yyyy HH:mm:ss");
					temp.setModified(sdf.format(fileList[i].lastModified()));
					fileInfo.add(temp);
				}
			}
		}

		ArrayList<DirectoryLevel> level = new ArrayList<DirectoryLevel>();
		DirectoryLevel root = new DirectoryLevel();
		root.setName("root");
		root.setPath("");
		level.add(root);
		String levelPath;

		if ((requestPath != null) && (!"".equals(requestPath))) {

			if ('/' == requestPath.charAt(0)) {
				levelPath = requestPath.substring(1);
			} else {
				levelPath = requestPath;
			}
			String[] pathSplit = levelPath.split("/");
			for (int i = 0; i < pathSplit.length; i++) {
				DirectoryLevel temp = new DirectoryLevel();
				temp.setName(pathSplit[i]);

				if (i == 0) {
					temp.setPath("/" + pathSplit[i]);
				} else {
					temp.setPath(level.get(i).getPath() + "/" + pathSplit[i]);
				}

				level.add(temp);
			}
		}

		sess.setAttribute("level", level);
		if (requestPath == null) {
			sess.setAttribute("currentDir", "");
		} else {
			sess.setAttribute("currentDir", requestPath);
		}

		Collections.sort(fileInfo, new Comparator<FileInformation>() {

			@Override
			public int compare(FileInformation o1, FileInformation o2) {
				if (o1.getIsDirectory() == true) {
					if (o2.getIsDirectory() == true) {
						int cpr = o1.getName().compareTo(o2.getName());
						if (cpr > 0) {
							return 1;
						} else {
							return -1;
						}
					} else {
						return -1;
					}
				} else {
					if (o2.getIsDirectory() == true) {
						return 1;
					} else {
						int cpr = o1.getName().compareTo(o2.getName());
						if (cpr > 0) {
							return 1;
						} else {
							return -1;
						}
					}
				}
			}

		});

		sess.setAttribute("fileInfo", fileInfo);
		RequestDispatcher dispatcher = req
				.getRequestDispatcher("pages/file_management.jsp");
		dispatcher.forward(req, resp);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init()
	 */
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}

}
